package com.lagou.handler;

import com.lagou.ioc.ApplicationContext;
import com.lagou.ioc.BeanWrap;
import com.lagou.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
         //1.判断当前的请求是否符合规则
        if (msg instanceof RpcRequest){
            RpcRequest rpcRequest = (RpcRequest) msg;

            String requestId = rpcRequest.getRequestId();
            String methodName = rpcRequest.getMethodName();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            Object[] parameters = rpcRequest.getParameters();

            BeanWrap beanWrap = ApplicationContext.getObjectById(requestId);
            if (beanWrap != null){
                Class<?> cls = beanWrap.getCls();
                Method method = cls.getMethod(methodName, parameterTypes);
                if (method != null){
                    Object result = method.invoke(beanWrap.getBeanInstance(), parameters);
                    System.out.println("执行结果:" + result);

                    // 返回字符串success
                    ctx.writeAndFlush("success");
                }
            }

        }
    }
}
